<?php

namespace app\api\service;

use app\api\model\User;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;

class RemindMessage extends WxMessage
{
    const DELIVERY_MSG_ID = '2gwdhJKxgMkkcbW4J_J9eHOf_0ryuzg9ubVAEVjNAGg';// 小程序模板消息ID号

    //    private $productName;
    //    private $devliveryTime;
    //    private $order

    public function sendRemindMessage($order, $tplJumpPage = '')
    {
        if (!$order) {
            throw new OrderException();
        }
        $tplJumpPage = '';
        $this->tplID = self::DELIVERY_MSG_ID;
        $this->formID = $order->prepay_id;
        $this->page = $tplJumpPage;
        $this->prepareMessageData($order);
        $this->emphasisKeyWord='';
        // return parent::sendMessage($this->getUserOpenID($order->user_id));
        $user = new User();
        $user_arr = $user->where('customer_service', '=', 2)->column('id');
        $user_arr = array_values($user_arr);
        $user_id = $user_arr[array_rand($user_arr, 1)];
        return parent::sendMessage($this->getUserOpenID($user_id));
    }

    private function prepareMessageData($order)
    {
        $snap_info = ($order->snap_address);
        $name = $snap_info->name;
        $pro_name = $order->snap_name;
        $order_no = $order->order_no;
        $order_status = config('setting.order_status_arr')[$order->status];
        $order_price = $order->total_price;
        $order_note = $order->note;
        if(empty($order_note)){
            $order_note = '买家提醒：请尽快发货';
        }
        $data = [
            'keyword1' => [
                'value' => $name,
            ],
            'keyword2' => [
                'value' => $pro_name,
            ],
            'keyword3' => [
                'value' => $order_no,
            ],
            'keyword4' => [
                'value' => $order_status,
            ],
            'keyword5' => [
                'value' => $order_price,
            ],
            'keyword6' => [
                'value' => $order_note,
            ]
        ];
        $this->data = $data;
    }

    private function getUserOpenID($uid)
    {
        $user = User::get($uid);
        if (!$user) {
            throw new UserException();
        }
        return $user->openid;
    }
}